package com.jfinal.plugin.spring;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.IDataSourceProvider;

public class SpringDataSourceProvider implements IDataSourceProvider {
	
	private ApplicationContext ctx;

	private static final String proxyDsName = "proxyDataSource";
	
	private String beanName;
	
	public SpringDataSourceProvider(String beanName){
		this.beanName = beanName;
	}
	
	public SpringDataSourceProvider(){
		this.beanName = proxyDsName;
	}
	
	@Override
	public DataSource getDataSource() {
		if(IocInterceptor.ctx==null){
			IocInterceptor.ctx = new FileSystemXmlApplicationContext(PathKit.getWebRootPath() + "/WEB-INF/applicationContext.xml");
		}
		ctx = IocInterceptor.ctx;
		DataSource ds = null;
		ds = (DataSource)ctx.getBean(beanName,TransactionAwareDataSourceProxy.class);
		return ds;
	}

}
